package tp1.presentacion.controlador;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import tp1.presentacion.modelo.TipoVagon;
import tp1.presentacion.modelo.TipoVagonLogic;

/**
 * Servlet implementation class TipoVagonController
 */
public class TipoVagonController extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public TipoVagonController() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String url = request.getPathInfo();
		if(url.equals("/listar")) {
			this.listarVagones(request, response);
		} else if(url.equals("/nuevo")) {
			response.sendRedirect("nuevoVagon.jsp");
		} else if(url.equals("/registrar")) {
			this.registrarTipoVagon(request, response);
		}
	}
	
	private void registrarTipoVagon(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		TipoVagonLogic tvLog = new TipoVagonLogic();
		String descTV = request.getParameter("descripcion");
		int recargo = Integer.parseInt(request.getParameter("recargo"));
		TipoVagon tv = new TipoVagon();
		tv.setCodigo(0);
		tv.setDescripcion(descTV);
		tv.setRecargo(recargo);
		tvLog.agregar(tv);
		response.sendRedirect("index.jsp");
	}
	private void listarVagones(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		TipoVagonLogic tvLog = new TipoVagonLogic();
		ArrayList<TipoVagon> tvs = tvLog.getTodos();
		request.setAttribute("vagones", tvs);
		RequestDispatcher rdis = request.getRequestDispatcher("/listVag.jsp");
		rdis.forward(request, response);		
	}
}